package com.web.controller;

import com.web.entity.Admin;
import com.web.entity.Result;
import com.web.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    //注册{"username":"丁小松","password":"123123", "role":"管理员"}
    //http://localhost:8080/admin/register
    @PostMapping("/register")
    public Result register(@RequestBody Admin admin) {
        log.info("用户名:{},密码:{}", admin.getUsername(), admin.getPassword());
        adminService.save(admin);
        return Result.success();
    }

    //管理员登录
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        log.info("管理员登录: 用户名:{}", admin.getUsername());
        Admin loginAdmin = adminService.login(admin);
        if (loginAdmin != null) {
            log.info("登录成功");
            return Result.success(loginAdmin);
        } else {
            log.info("登录失败，用户名或密码错误");
            return Result.error("用户名或密码错误");
        }
    }

    //删除管理员
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        adminService.delete(id);
        return Result.success("删除成功");
    }

    //修改管理员
    //http://localhost:8080/admin/1
    //1.根据id查询管理员信息
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        log.info("根据id查询管理员信息:{}", id);
        Admin admin = adminService.findById(id);
        return Result.success(admin);
    }
    //http://localhost:8080/admin/update?id=1&username=钟东方&password=123123&role=管理员
    //2.修改管理员信息
    @PostMapping("/update")
    public Result update(@RequestBody Admin admin) {
        adminService.update(admin);
        return Result.success();
    }


    //查询所有管理员信息
    @GetMapping("/list")
    public Result findAll() {
        List<Admin> adminList = adminService.findAll();
        return Result.success(adminList);
    }

}
